package com.sas.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableImage;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import net.coobird.thumbnailator.Thumbnails;
import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.sas.entity.Shangpin;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sas.entity.Chukudan;
import com.sas.entity.Page;
import com.sas.service.ShangpinService;

@Controller
@RequestMapping("Shangpin.do")
public class ShangpinController {
	
	public String getMsg() {
		return msg;
	}


	public void setMsg(String msg) {
		this.msg = msg;
	}

	private String msg=null;
	
	@Autowired
	ShangpinService ShangpinService;
    //分页显示
	@RequestMapping(params="method=selectByShangpin")
	public String selectByShangpin(String index,String gysname,String price,String spname,String spno,String size,HttpSession session) throws Exception{
		
		System.out.println("进入方法");
		int price_1 = 0;
		//int id_int = 0;
		if(gysname!=null&&price!=null){
			if(price!=""){
				price_1 = Integer.parseInt(price);
			}
			
		}
		Page p = new Page();
		//每页条数
		p.setSize(20);
		//调用service持久话数据
		Integer sum = ShangpinService.selectCount();
		System.out.println("大小1"+sum);
		//3��ǰҳ
		Integer pages = sum%p.getSize()!=0?sum/p.getSize()+1:sum/p.getSize();
		
		p.setCount(pages);
		int index_int = 1;
		if(index==null||index==""){
			index_int = 1;
		}else{
			index_int = Integer.parseInt(index);
			if(index_int<=0){
				index_int = 1;
			}
			if(index_int > p.getCount()){
				index_int = p.getCount();
			}
		}
		
		p.setIndex(index_int);
	
		Shangpin s = new Shangpin(0, gysname, price_1,spname,spno,size);
		List<Shangpin> list =ShangpinService.selectByShangpin(s,p);
		System.out.println("大小"+list.size());
		session.setAttribute("list", list);
		session.setAttribute("page", p);
		
		return "showShangpin";
		
	}
	
	
	//全显示不分页action
//	@RequestMapping(params="method=getAll")
//	public String selectShangpin(HttpSession session){
//		List<Shangpin> list = ShangpinService.selectShangpin();
//		session.setAttribute("list", list);
//	
//		return "showShangpin";
//	}
	//删除action
	@RequestMapping(params="method=deleteShangpin", value="/redirect")
	public String deleteShangpin(String id,HttpSession session){
		Shangpin Shangpin=new Shangpin();	
		int id_i=Integer.parseInt(id);
		Shangpin.setId(id_i);
		
		int is;
		try {
			is = ShangpinService.deleteShangpin(Shangpin);
			//刷新 页面
			return "redirect:/Shangpin.do?method=selectByShangpin";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			session.setAttribute("msg", "删除失败");
			
			e.printStackTrace();
			return "showShangpin";
		}
		
		
	}
	
	@Cacheable(value="accountCache")
	@RequestMapping(params="method=insertIn")
    public void insertStudentss( HttpServletRequest request,HttpSession session,HttpServletResponse response) throws IOException {
		System.out.println("异步存储后台");
		//Shangpin in=new Shangpin();
		List<Chukudan> list_1 =new ArrayList<Chukudan>();
		String dss = request.getParameter("data1");
		System.out.println("异步存储后台1"+dss);
		JSONArray jsonArray = JSONArray.fromObject(dss);
		@SuppressWarnings("unchecked")
		List<Chukudan> lists = JSONArray.toList(jsonArray, Chukudan.class);
		for(Chukudan cc: lists){
			cc.getGysname();
			cc.getSpname();
			cc.getUrl();
			cc.getSpsl();
			String format = new SimpleDateFormat("yyyy-HH-dd HH:mm:ss").format(new Date());
			cc.setTime(format);
			list_1.add(cc);
		}
		
		int insertList = 0;
		try {
			int truncate = ShangpinService.truncate();
			insertList = ShangpinService.insertList(lists);
			ShangpinService.insertList1(list_1);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("异步存储后台出错"+e);
			e.printStackTrace();
		}
		
		ObjectMapper mapper = new ObjectMapper();    //提供java-json相互转换功能的类
		 
		  String json = mapper.writeValueAsString(insertList);    //将list中的对象转换为Json格式的数组	     
		    // System.out.println(json);	        
		        //将json数据返回给客户端
		      response.setContentType("text/html; charset=utf-8");
		       response.getWriter().write(json);  
		
	}
	@RequestMapping(params="method=dayinchukudan")
	public void dayinchukudan(HttpServletResponse response) throws Exception{
		List<Chukudan> list = ShangpinService.selectChukudan();
		//
		response.setContentType("application/vnd.ms-excel");
		Date date = new Date();//设置日期
		DateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//ʱ���ʽ��
		String d = dFormat.format(date);//截取日期
		String title = d+"出库单";
		//�ļ���
		String fileName = URLEncoder.encode("出库单","utf-8");
		response.setHeader("Content-disposition", "attachment;fileName="+fileName+".xls");
		//输出流
		OutputStream out = response.getOutputStream();
		
		WritableWorkbook wb = Workbook.createWorkbook(out);
		WritableSheet sheet = wb.createSheet("出库单", 0);
		sheet.getSettings().setDefaultColumnWidth(30);//50*256
		sheet.getSettings().setDefaultRowHeight(10);
		
		WritableFont font = new WritableFont(WritableFont.ARIAL,16,WritableFont.NO_BOLD);
		
		WritableCellFormat format = new WritableCellFormat(font);
		
		format.setBorder(Border.ALL, BorderLineStyle.THIN);
		
		format.setAlignment(Alignment.CENTRE);
		
		format.setWrap(true);
		
		WritableFont font1 = new WritableFont(WritableFont.ARIAL,30,WritableFont.BOLD);
		WritableCellFormat format1 = new WritableCellFormat(font1);
		format1.setAlignment(Alignment.CENTRE);
		
		sheet.mergeCells(0, 0, 2, 0);
		Label t  = new Label(0,0,title,format1);
		sheet.addCell(t);
		
	
		Label t1 = new Label(0,1,"供应商名字",format);
		Label t2 = new Label(1,1,"商品名字",format);		
		Label t3 = new Label(2,1,"地址",format);
		Label t4 = new Label(3,1,"备注",format);
		sheet.addCell(t1);
		sheet.addCell(t2);
		sheet.addCell(t3);
		sheet.addCell(t4);				
		int i = 0;		
		for (Chukudan Shangpin : list) {			
			Label c1 = new Label(0,i+2,Shangpin.getGysname()+"",format);
			Label c2 = new Label(1,i+2,Shangpin.getSpname()+"",format);
			Label c3 = new Label(2,i+2,Shangpin.getUrl()+"",format);
			Label c4 = new Label(3,i+2,Shangpin.getSpsl()+"",format);	
			sheet.addCell(c1);
			sheet.addCell(c2);
			sheet.addCell(c3);
			sheet.addCell(c4);
			i++;
		}	
		wb.write();
		wb.close();
		out.flush();
		out.close();
	}
	
//	//增加action
//	@RequestMapping(params="method=insertShangpins")
//    public String insertStudents( HttpServletRequest request,HttpSession session) {
//		System.out.println("异步存储后台");
//	//	Shangpin in=new Shangpin();
//		List<Chukudan> in=new ArrayList<Chukudan>();
//		String dss = request.getParameter("data1");
//		System.out.println("异步存储后台1"+dss);
//		JSONArray jsonArray = JSONArray.fromObject(dss);
//		String gysname = "";
//		String spname = "";
//		String url = "";
//		String spsl = "";
//		for (int i = 0; i < jsonArray.size(); i++) {
//		JSONObject jsonJ = jsonArray.getJSONObject(i);
//		gysname = jsonJ.getString("gysname");
//		spname = jsonJ.getString("spname");
//		url = jsonJ.getString("url");
//		spsl = jsonJ.getString("spsl");
//	//	in.setName(name);
//		//in.setage(i);
//		ShangpinService.insertShangpin(in);
//		System.out.println("异步存储后台数据"+spsl+"//"+i);
//		
//		}
//
//		//持久层
//		int i = ShangpinService.insertShangpin(in);
//		
//		if(i==1){
//			System.out.println("成功");
//		}else{
//			System.out.println("失败");
//		}
//		session.setAttribute("insert", i);
//		return "insertResult";
//	}
//	
	//增加action
	
	@RequestMapping(params="method=insertShangpin", value="/redirect")
    public String insertStudent(String gysname,String spname,String spno,String color,String size,String chengfen,String price,String url,MultipartFile tupianurl,String beizhu,HttpSession session) throws IllegalStateException, IOException {
		
		String aa=null;	
		String substring =null;
		System.out.println("接收参数"+tupianurl);
		if (!tupianurl.isEmpty()) { 
			String paths = "E:\\io\\";
            String path = "E:\\io\\image\\";
            String originalFileName = tupianurl.getOriginalFilename();
            // 新的图片名称
            aa = UUID.randomUUID() + originalFileName.substring(originalFileName.lastIndexOf("."));
            // 新的图片
            File newFile = new File(paths + aa);
            // 将内存中的数据写入磁盘
            tupianurl.transferTo(newFile);
      // System.out.println("aa"+aa.lastIndexOf("."));      
        substring = aa.substring(aa.indexOf(0)+1, aa.lastIndexOf("."));
           BufferedImage thumbnail = Thumbnails.of(paths + aa).size(200, 100).asBufferedImage();
           ImageIO.write(thumbnail, "png", new File(path + substring+".png"));
           new File(paths+aa).delete();//删除原先的图片  
        }
		int price_1 = Integer.parseInt(price);
		Shangpin in=new Shangpin(gysname,spname,spno,color,size,chengfen,price_1,url,substring+".png",beizhu);	
		//持久层
		int i;
		try {
			i = ShangpinService.insertShangpin(in);
			System.out.println("操作结果"+i);
			return "redirect:/Shangpin.do?method=selectByShangpin";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			session.setAttribute("msg", "增加失败");
			
			e.printStackTrace();
			return "showShangpin";
		}
		
	}
	
	//修改
	
	 @RequestMapping(params="method=updateShangpin", value="/redirect")
	    public String updateShangpin(String gysname,String spname,HttpSession session,HttpServletRequest request) {
			Shangpin Shangpin=new Shangpin();
			String id=request.getParameter("id");
	    //System.out.println("id"+id+name+age);
			int id_int = Integer.parseInt(id);
		//	int age_int = Integer.parseInt(age);
		//System.out.println("age"+id_int+age_int);
		   Shangpin.setId(id_int);
		    Shangpin.setGysname(gysname);
		    Shangpin.setSpname(spname);
			
			int i;
			try {
				i = ShangpinService.updateShangpin(Shangpin);
				return "redirect:/Shangpin.do?method=selectByShangpin";
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				session.setAttribute("msg", "修改失败");
				return "showShangpin";
			}
			
		
			
		
		}
	
	@RequestMapping(params="method=downLoad")
	public void downLoadShangpin(HttpServletResponse response) throws Exception{
		List<Shangpin> list = ShangpinService.selectShangpin();
		//
		response.setContentType("application/vnd.ms-excel");
		Date date = new Date();//设置日期
		DateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//ʱ���ʽ��
		String d = dFormat.format(date);//截取日期
		String title = d+"标题";
		//�ļ���
		String fileName = URLEncoder.encode("标题","utf-8");
		response.setHeader("Content-disposition", "attachment;fileName="+fileName+".xls");
		//输出流
		OutputStream out = response.getOutputStream();
		
		WritableWorkbook wb = Workbook.createWorkbook(out);
		WritableSheet sheet = wb.createSheet("标题", 0);
		sheet.getSettings().setDefaultColumnWidth(15);//50*256
		//sheet.getSettings().setDefaultRowHeight((short) (300 * 256)); //设置默认行高，表示2个字符的高度
		WritableFont font = new WritableFont(WritableFont.ARIAL,16,WritableFont.NO_BOLD);
		
		WritableCellFormat format = new WritableCellFormat(font);
		
		format.setBorder(Border.ALL, BorderLineStyle.THIN);
		
		format.setAlignment(Alignment.CENTRE);
		
		format.setWrap(true);
		
		WritableFont font1 = new WritableFont(WritableFont.ARIAL,30,WritableFont.BOLD);
		WritableCellFormat format1 = new WritableCellFormat(font1);
		format1.setAlignment(Alignment.CENTRE);
		
		sheet.mergeCells(0, 0, 2, 0);
		Label t  = new Label(0,0,title,format1);
		sheet.addCell(t);
		
		Label t1 = new Label(0,1,"编号",format);
		Label t2 = new Label(1,1,"供应商名字",format);
		Label t3 = new Label(2,1,"商品名字",format);
		Label t4 = new Label(3,1,"商品编号",format);
		Label t5 = new Label(4,1,"商品颜色",format);
		Label t6 = new Label(5,1,"尺寸",format);
		Label t7 = new Label(6,1,"成分",format);
		Label t8 = new Label(7,1,"价格",format);
		Label t9 = new Label(8,1,"地址",format);
		Label t10 = new Label(9,1,"图片",format);
		Label t11 = new Label(10,1,"备注",format);
		sheet.addCell(t1);
		sheet.addCell(t2);
		sheet.addCell(t3);
		sheet.addCell(t4);
		sheet.addCell(t5);
		sheet.addCell(t6);
		sheet.addCell(t7);
		sheet.addCell(t8);
		sheet.addCell(t9);
		sheet.addCell(t10);
		sheet.addCell(t11);		
		int i = 0;
	//	CellView cellView = new CellView();  
	   //  cellView.setAutosize(true); //设置自动大小
		// 设置B列的宽度为30*256；
		
		for (Shangpin Shangpin : list) {
			Label c1 = new Label(0,i+2,Shangpin.getId()+"",format);
			Label c2 = new Label(1,i+2,Shangpin.getGysname()+"",format);
			Label c3 = new Label(2,i+2,Shangpin.getSpname()+"",format);
			Label c4 = new Label(3,i+2,Shangpin.getSpno()+"",format);
			Label c5 = new Label(4,i+2,Shangpin.getColor()+"",format);
			Label c6 = new Label(5,i+2,Shangpin.getSize()+"",format);
			Label c7 = new Label(6,i+2,Shangpin.getChengfen()+"",format);
			Label c8 = new Label(7,i+2,Shangpin.getPrice()+"",format);
			Label c9 = new Label(8,i+2,Shangpin.getUrl()+"",format);
		  //Label c10 = new Label(9,i+2,Shangpin.getTupianurl()+"",format);
			Label c11 = new Label(10,i+2,Shangpin.getBeizhu()+"",format);
			
			sheet.addCell(c1);
			sheet.addCell(c2);
			sheet.addCell(c3);
			sheet.addCell(c4);
			sheet.addCell(c5);
			sheet.addCell(c6);
			sheet.addCell(c7);
			sheet.addCell(c8);
			sheet.addCell(c9);
			//获取本地图片大小（尺寸）
			File picture=new File("E:\\io\\image\\"+Shangpin.getTupianurl());
			BufferedImage sourceImg=ImageIO.read(new FileInputStream(picture));
			int srcWidth= sourceImg.getWidth();// 图片宽, 像素
			int srcHeight = sourceImg.getHeight();// 图片高, 像素
            System.out.println("宽"+srcWidth+"高"+srcHeight);
          //  srcHeight=(int)Math.round((srcHeight*(40*13)*1.0/srcWidth));
			sheet.addImage(new WritableImage(9,i+2,1,1,new File("E:\\io\\image\\"+Shangpin.getTupianurl())));
			//sheet.addCell(c10);
			sheet.addCell(c11);
			//设置行高 第几行 多高 是否隐藏
			sheet.setRowView(i+2,2000,false);//正文行高20
			i++;
		}
	
		wb.write();
		wb.close();
		out.flush();
		out.close();
	}
	

}
